package com.copa.utils;

import com.alibaba.fastjson.JSONObject;
import com.copa.entity.IHttpMessage;
import com.copa.entity.Position;

import static com.copa.constant.MessageType.*;

/**
 * @author copa
 * @createDate 2022-03-02 22:51
 * @function
 */
public class JsonUtil {

    public static IHttpMessage dealMsg(String json) {
        String tempJson = json.substring(0, json.indexOf(",\"msg\"")) + "}";
        JSONObject jsonObject = (JSONObject) JSONObject.parse(tempJson);
        IHttpMessage message = JSONObject.toJavaObject(jsonObject, IHttpMessage.class);
        if (PIC_MESSAGE == message.getType()
                || VOICE_MESSAGE == message.getType()
                || VIDEO_MESSAGE == message.getType()
                || (LINK_MESSAGE == message.getType() && !json.contains("<title>"))) {
            message.setMsg(json.substring(json.indexOf(",\"msg\"") + 8, json.length() - 2));
        } else if (POSITION_MESSAGE == message.getType()) {
            jsonObject = (JSONObject) JSONObject.parse(json);
            Position position = JSONObject.toJavaObject(jsonObject.getJSONObject("msg"), Position.class);
            message.setMsg(position.getTitle()
                    + " " + position.getDesc()
                    + " (" + position.getY()
                    + "," + position.getX() + ")");
        } else {
            jsonObject = (JSONObject) JSONObject.parse(json);
            message = JSONObject.toJavaObject(jsonObject, IHttpMessage.class);
        }
        return message;
    }
}
